import {Injectable} from 'angular2/core';
import {Http} from 'angular2/http';

@Injectable()
export class Common{
    static get parameters() {
        return [[Http]];
    }
    
    constructor(http) {
        this.http = http;
    }
    
    getTodayArticles() {
        // already loaded data
        if(this.articles){
            return Promise.resolve(this.articles);
        }
        
        // don't have data 
        return new Promise(resolve=>{
            this.http.get('http://news-at.zhihu.com/api/4/news/latest').subscribe(res=>{
                this.articles = this.processData(res.json());
                resolve(this.articles);
            });
        });
    }
    
    processData(data){
        let top_stories = [];
        let stories = [];
        
        data.top_stories.forEach(top=>{
            top_stories.push({
                id:top.id,
                image:top.image,
                title:top.title
            });
        });
        
        data.stories.forEach(s=>{
            stories.push({
                id:s.id,
                title:s.title,
                image:s.images[0]
            });
        });
        
        return {top_stories:top_stories,stories:stories}
    }
    
    getArticleContentByID(articleID) {
        if(articleID){
            return new Promise(resolve=>{
                this.http.get('http://news-at.zhihu.com/api/4/news/'+articleID).subscribe(res=>{
                    this.articleContent = res.json();
                    resolve(this.articleContent);
                });
            });
        }else{
            return new Promise(resolve=>{
                resolve({
                    body:'参数格式不正确',
                    css:'',
                    id:'',
                    image:'',
                    image_source:'',
                    images:[],
                    js:[],
                    share_url:'',
                    title:'Not Found',
                    type:0
                });
            });
        }
    }
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
}